import {defineStore} from "pinia";
import {ref} from "vue"
import type{MenuItem} from "@/types/user"
export const useTabsStore=defineStore("tabs",()=>{
    const tabs=ref<MenuItem[]>([]);
    const currentTab=ref<{name:string,url:string}>({name:"",url:""})

    const addTab=(name:string,url:string,icon:string)=>{
        if(!tabs.value.some((tab)=>tab.url===url)){
            tabs.value.push({name,url,icon})
        }
    }

    const setCurrentTab=(name:string,url:string)=>{
        currentTab.value={name,url}
    }

    const removeTab=(name:string)=>{
        //如果删除的是高亮的
        if(currentTab.value.name===name){
            const currentIndex=tabs.value.findIndex(tab=>tab.name===name);
            if(currentIndex!=0){
                currentTab.value=tabs.value[currentIndex-1]
            }else{
                return 
            }
           
        }

        tabs.value=tabs.value.filter(tab=>tab.name!==name)
    }

    // 关闭除首页以外的所有选项卡
    const clearAllTabsExceptHome = () => {
        // 保留首页选项卡（假设首页的name是"首页"或"主页"）
        const homeTab = tabs.value.find(tab => 
            tab.name === "首页" || 
            tab.name === "主页" || 
            tab.name === "Home" ||
            tab.url === "/" ||
            tab.url === "/dashboard"
        )
        
        // 清空所有选项卡
        tabs.value = []
        
        // 如果有首页选项卡，重新添加
        if (homeTab) {
            tabs.value.push(homeTab)
            // 设置当前选项卡为首页
            currentTab.value = { name: homeTab.name, url: homeTab.url }
        } else {
            // 如果没有找到首页，清空当前选项卡
            currentTab.value = { name: "", url: "" }
        }
    }


    return {tabs,addTab,currentTab,setCurrentTab,removeTab,clearAllTabsExceptHome}
    
})
